package com.sfc.spiderweb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfc.spiderweb.entity.AmazonTransferInfo;
import com.sfc.spiderweb.entity.AmazonViolationDataInfo;
import com.sfc.spiderweb.entity.PlatformRdpUser;
import com.sfc.spiderweb.mapper.PlatformRdpUserMapper;
import com.sfc.spiderweb.service.PlatformRdpUserService;
import com.sfc.spiderweb.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 李振伟(Earl Li)
 * @title: PlatformRdpUserServiceImpl
 * @projectName spider-web
 * @description: ${description}
 * @date 2020/1/1513:51
 */
@Service
@Slf4j
public class PlatformRdpUserServiceImpl extends ServiceImpl<PlatformRdpUserMapper, PlatformRdpUser> implements PlatformRdpUserService {


    @Value("${ftp.url}")
    private String ftpUrl;
    @Value("${ftp.port}")
    private Integer ftpPort;
    @Value("${ftp.user}")
    private String ftpUser;
    @Value("${ftp.password}")
    private String ftpPassword;
    @Value("${mail.sender}")
    private String mailSender;
    @Value("${mail.password}")
    private String mailPassword;
    @Value("${mail.finance-amazon-transfer}")
    private String mailFinanceAmazonTransfer;
    @Value("${mail.finance-amazon-invoice}")
    private String mailFinanceAmazonInvoice;
    @Value("${mail.finance-amazon-violationdata}")
    private String mailFinanceViolationData;
    @Value("${mail.send-emil-url}")
    private String emailUrl;

    private String nowDateStr;

    @Override
    public void sendTransferMail() throws Exception {
        String dateStr = DateUtil.getNetTime();
        Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");
        this.nowDateStr = DateUtil.formatDate("yyyy-MM-dd", date);
        List<List<String>> transferListInfo = new ArrayList<>();
        final String ftpPath = "/financeFtp/amazon_transfer/" + nowDateStr + "/";
        final String outPath = "\\amazon-transfer.xlsx";
        QueryWrapper<PlatformRdpUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PlatformRdpUser::getPlatform, "amazon");
        wrapper.lambda().eq(PlatformRdpUser::getState, "1");
        wrapper.lambda().eq(PlatformRdpUser::getStatus, "1");
        List<PlatformRdpUser> list = this.list(wrapper);

        List<String> topList = Arrays.asList("账号", "Transfer Info", "Transfer Amount", "Transfer Name");
        transferListInfo.add(topList);
        if (CollectionUtils.isEmpty(list)) {
            log.error("无Amazon账号信息");
            return;
        }
        FTPClient ftp = FTPUtil.getFTPClient(ftpUrl, ftpPort, ftpUser, ftpPassword);
        List<String> collect = list.stream().map(x -> x.getPlatformCode().toLowerCase()).collect(Collectors.toList());
        List<FTPUtil.FilePath> filePathList = FTPUtil.getFilePath(ftp, ftpPath);
        List<String> ftpFileName = filePathList.stream().map(FTPUtil.FilePath::getName).collect(Collectors.toList());
        Map<String, String> map = FTPUtil.readFileByfolderInFtp(ftp, ftpPath);
        for (String s : collect) {
            //String fileName = s + "-TransferInfo-" + nowDateStr + ".txt";
            List<String> collect1 = ftpFileName.stream().filter(f -> {
                String fileName = f.substring(0, f.indexOf("-"));
                if (fileName.equalsIgnoreCase(s)) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect1)) {
                for (String s1 : collect1) {
                    String content = map.get(s1);
                    AmazonTransferInfo amazonTransferInfo = JSONObject.parseObject(content, AmazonTransferInfo.class);
                    if (!StringUtils.isEmpty(amazonTransferInfo)) {
                        transferListInfo.add(Arrays.asList(amazonTransferInfo.getAccount(), amazonTransferInfo.getTransferMessage(), amazonTransferInfo.getCurrentBalanceValue(), amazonTransferInfo.getTransferName()));
                    }
                }
            } else {
                transferListInfo.add(Arrays.asList(s, "无", "无"));
            }
        }
        byte[] amazonTransfers = ExcelUtils.writeExcel1(outPath, Arrays.asList("amazon-transfer"), Arrays.asList(transferListInfo));
        sendMail(amazonTransfers, 1);
    }

    @Override
    public void sendAmazonViolationData() throws Exception {
        String dateStr = DateUtil.getNetTime();
        Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");
        this.nowDateStr = DateUtil.formatDate("yyyy-MM-dd", date);
        List<List<String>> amazonViolationDataListInfo = new ArrayList<>();
        List<String> title = Arrays.asList("账号", "日期", "类型", "有无数据", "reason", "平台侵权日期", "affected", "actionTaken", "nextSteps");
        amazonViolationDataListInfo.add(title);
        final String ftpPath = "/financeFtp/amazon_violation_data/" + nowDateStr + "/";
        final String outPath = "\\amazon-violation-data.xlsx";
        FTPClient ftp = FTPUtil.getFTPClient(ftpUrl, ftpPort, ftpUser, ftpPassword);
        Map<String, String> map = FTPUtil.readFileByfolderInFtp(ftp, ftpPath);
        for (String key : map.keySet()) {
            String content = map.get(key);
            System.out.println("key="+key);
            List<AmazonViolationDataInfo> amazonViolationDataInfos = JSONObject.parseArray(content, AmazonViolationDataInfo.class);
            for (AmazonViolationDataInfo dataInfo : amazonViolationDataInfos) {
                List<String> list = new ArrayList<>();
                list.add(dataInfo.getDownloadFileName());
                list.add(dataInfo.getThisDay());
                list.add(dataInfo.getType());
                list.add(dataInfo.getState());
                list.add(dataInfo.getReason());
                list.add(dataInfo.getDate());
                list.add(dataInfo.getAffected());
                list.add(dataInfo.getActionTaken());
                list.add(dataInfo.getNextSteps());
                amazonViolationDataListInfo.add(list);
            }
        }
        byte[] amazonViolationData = ExcelUtils.writeExcel1(outPath, Arrays.asList("amazon-violation-data"), Arrays.asList(amazonViolationDataListInfo));
        sendMail(amazonViolationData, 2);
    }

    @Override
    public void sendAmazonAmazonUploadInvoice() throws Exception {
        String dateStr = DateUtil.getNetTime();
        Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");
        this.nowDateStr = DateUtil.formatDate("yyyy-MM-dd", date);
        List<List<String>> invoiceListInfo = new ArrayList<>();
        final String ftpPath = "/financeFtp/amazon_upload_invoice/" + nowDateStr + "/";
        final String outPath = "\\amazon-upload-invoice.xlsx";
        List<String> topList = Arrays.asList("账号", "上传发票订单", "是否上传成功");
        invoiceListInfo.add(topList);

        FTPClient ftp = FTPUtil.getFTPClient(ftpUrl, ftpPort, ftpUser, ftpPassword);
        List<FTPUtil.FilePath> filePathList = FTPUtil.getFilePath(ftp, ftpPath);
        if (!CollectionUtils.isEmpty(filePathList)) {
            for (FTPUtil.FilePath filePath : filePathList) {
                String account = filePath.getName();
                List<FTPUtil.FilePath> childList = FTPUtil.getFilePath(ftp, filePath.getAbsolute());
                List<String> downFile = childList.stream().filter(f -> !f.getName().contains("finish")).map(m -> m.getName().replaceAll(".pdf", "")).collect(Collectors.toList());
                List<String> uploadFile = childList.stream().filter(f -> f.getName().contains("finish")).map(m -> m.getName().substring(m.getName().indexOf("-") + 1).replaceAll(".pdf", "")).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(downFile)) {
                    for (String s : downFile) {
                        String uploadOrder = s;
                        String result;
                        if (uploadFile.contains(s)) {
                            result = "上传成功";
                        } else {
                            result = "上传失败";
                        }
                        invoiceListInfo.add(Arrays.asList(account, uploadOrder, result));
                    }
                }
            }
        }
        byte[] amazonTransfers = ExcelUtils.writeExcel1(outPath, Arrays.asList("amazon-invoice"), Arrays.asList(invoiceListInfo));
        sendMail(amazonTransfers, 3);
    }

    @Override
    public void rdp() {
        String adminFilePath = "D:\\RDP\\admin82\\";
        String userFilePath = "D:\\RDP\\userRdp82\\";
        List<String> platformList = Arrays.asList("aliexpress", "alipay", "amazon", "ebay", "lazada", "payoneer", "paypal", "wish");
        FileUtil.deleteAll(adminFilePath);
        FileUtil.deleteAll(userFilePath);
        for (String platform : platformList) {
            QueryWrapper<PlatformRdpUser> wrapper = new QueryWrapper<>();
            //wrapper.lambda().eq(PlatformRdpUser::getState, "1");
            wrapper.lambda().eq(PlatformRdpUser::getStatus, "1");
            wrapper.lambda().eq(PlatformRdpUser::getPlatform, platform);
            List<PlatformRdpUser> list = this.list(wrapper);

            Map<String, List<PlatformRdpUser>> collect = list.stream().filter(f -> !StringUtils.isEmpty(f.getIp())).collect(Collectors.groupingBy(PlatformRdpUser::getIp));
            File adminFile = new File("src/main/resources/82-adminRDP.txt");
            File userFile = new File("src/main/resources/82rdp.txt");
            String adminRdpTxt = FileUtil.readTxt(adminFile);
            String userRdpTxt = FileUtil.readTxt(userFile);
            for (String s : collect.keySet()) {
                String adminCount = adminRdpTxt.replaceAll("@hostIp", s);
                String fileName = adminFilePath + collect.get(s).get(0).getPlatform() + "\\" + s + "-administrator.RDP";
                log.info(fileName);
                FileUtil.writeTxtAsUtf8(fileName, adminCount);
            }
            for (PlatformRdpUser platformRdpUser : list) {
                String userCount = userRdpTxt.replaceAll("@hostIp", platformRdpUser.getIp()).replaceAll("@username", platformRdpUser.getWinUser());
                String platfrom = platformRdpUser.getPlatform();
                String fileName = userFilePath + platfrom + "\\" + platformRdpUser.getRdpFileName();
                if (platfrom.toLowerCase().equals("amazon")) {
                    if (!StringUtils.isEmpty(platformRdpUser.getDownloadFileName()) && platformRdpUser.getDownloadFileName().toLowerCase().contains("ssp")) {
                        fileName = userFilePath + platfrom + "\\ssp\\" + platformRdpUser.getRdpFileName();
                    } else {
                        fileName = userFilePath + platfrom + "\\santai\\" + platformRdpUser.getRdpFileName();
                    }
                }

                FileUtil.writeTxtAsUtf8(fileName, userCount);

            }
        }
    }

    public void sendMail(byte[] amazonTransfers, Integer type) {
        Map<String, Object> otherParam = new HashMap<>();
        // 发送人邮箱
        otherParam.put("emailUsername", mailSender);
        //抄送
        //otherParam.put("ccList", mailFinance1);
        // 邮箱密码
        otherParam.put("emailPassword", mailPassword);
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (1 == type) {
            otherParam.put("sender", nowDateStr + "amazon日转款详情");
            otherParam.put("subject", "Earl");
            otherParam.put("content", nowDateStr + "amazon日转款详情");
            // 接收人邮箱
            otherParam.put("receiveList", String.join(",", Arrays.asList(mailFinanceAmazonTransfer.split(","))));
            // 设置文件名称
            map.put("name", "amazonTransfer-" + nowDateStr + ".xlsx");
        } else if (2 == type) {
            otherParam.put("sender", nowDateStr + "amazon账号违规数据详情");
            otherParam.put("subject", "Earl");
            otherParam.put("content", nowDateStr + "amazon账号违规数据详情");
            // 接收人邮箱
            otherParam.put("receiveList", String.join(",", Arrays.asList(mailFinanceViolationData.split(","))));
            // 设置文件名称
            map.put("name", "amazonViolationData-" + nowDateStr + ".xlsx");
        } else if (3 == type) {
            otherParam.put("sender", nowDateStr + "amazon发票上传数据详情");
            otherParam.put("subject", "Earl");
            otherParam.put("content", nowDateStr + "amazon发票上传数据详情");
            // 接收人邮箱
            otherParam.put("receiveList", String.join(",", Arrays.asList(mailFinanceAmazonInvoice.split(","))));
            // 设置文件名称
            map.put("name", "amazonUploadInvoice-" + nowDateStr + ".xlsx");
        } else {
            //TODO
        }
        // 设置文件base64
        map.put("base64", Base64.getEncoder().encodeToString(amazonTransfers));
        list.add(map);
        otherParam.put("fileList", list);
        Object param = JSONObject.toJSON(otherParam);
        log.info("调用邮件接口:{}", param);
        String mailResult = HttpClient.doPost(emailUrl, param.toString(), "POST");
        log.info("返回邮件接口:{}", mailResult);
    }
}
